<template>
  <div class="biaoge">
    <!-- 页面头部标题 -->
    <div class="head">考试管理</div>
    <el-tabs  v-model="activeName" type="border-card">
      <el-tab-pane
        label="试卷信息"
        name="first"
        tab-click="setshuju1"
      >
        <!-- 搜索表单 -->
        <el-form :inline="true" class="demo-form-inline">
          <!-- 试卷名称搜索框 -->
          <el-input
            v-model="saosuo.xianguan"
            placeholder="请输入试卷名称"
            style="margin-bottom: 29px"
          />

          <!-- 搜索按钮 -->
          <el-button type="primary" class="search-button" @click="performSearch"
            >搜索</el-button
          >
        </el-form>
        <!-- 试卷表格 -->
        <el-table :data="tableData" style="width: 120%">
          <!-- 试卷名称列 -->
          <el-table-column
            prop="examination_name"
            label="试卷名称"
            align="center"
            width="180"
            sortable
          />

          <!-- 试卷类型列 -->
          <el-table-column
            prop="direction_name"
            label="试卷类型"
            align="center"
            width="180"
          />

          <!-- 总分列 -->
          <el-table-column
            prop="examination_score"
            label="总分"
            align="center"
            width="180"
          />

          <!-- 编辑时间列 -->
          <el-table-column
            prop="examination_time"
            label="编辑时间"
            align="center"
            width="180"
            sortable
          >
            <template #default="scope">
              <!-- 格式化显示编辑时间 -->
              {{ formattedCreateTime(scope.row.examination_time) }}
            </template>
          </el-table-column>

          <!-- 编辑人列 -->
          <el-table-column
            prop="nick_name"
            label="编辑人"
            align="center"
            width="180"
          />

          <!-- 操作列 -->
          <el-table-column label="操作" align="center" width="230">
            <template #default="scope">
              <!-- 编辑按钮 -->
              <el-button
                plain
                type="danger"
                size="small"
                :class="!scope.row.hasResult ? 'button2' : 'button1'"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <!-- 预览按钮 -->
              <!-- <el-button plain type="warning" size="small" @click="handleLook(scope.$index, scope.row)">预览</el-button> -->

              <!-- 创建按钮 -->
              <el-button
                plain
                type="success"
                size="small"
                :class="!scope.row.hasResult ? 'button2' : 'button1'"
                @click="handlePreview(scope.$index, scope.row)"
                >创建</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
          v-model:current-page="saosuo.pageNum"
          v-model:page-size="saosuo.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="saosuo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; justify-content: center"
        />
      </el-tab-pane>

      <!--考试表单-->
      <el-tab-pane label="考试信息" name="second" tab-click="setexamRoom02()">
        <el-table :data="tableData02" style="width: 100%">
          <el-table-column prop="exam_id" label="试卷编号" width="100" />
          <el-table-column prop="exam_name" label="考试名称" width="180" />
          <el-table-column
            prop="examination_name"
            label="试卷名称"
            width="150"
          />

          <el-table-column prop="direction_name" label="试卷类型" width="140" />

          <el-table-column
            prop="start_time"
            label="开始时间"
            width="180"
            sortable
          >
            <template #default="scope">
              <!-- 格式化显示编辑时间 -->
              {{ formattedCreateTime2(scope.row.start_time) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="end_time"
            label="结束时间"
            width="180"
            sortable
          >
            <template #default="scope">
              <!-- 格式化显示编辑时间 -->
              {{ formattedCreateTime2(scope.row.end_time) }}
            </template>
          </el-table-column>

          <el-table-column prop="address" label="操作">
            <template #default="scope">
              <el-button
                plain
                type="warning"
                size="small"
                @click="bianji(scope.$index, scope.row)"
                :class="!scope.row.hasResult ? 'button2' : 'button1'"
                >编辑</el-button
              >
              <el-button
                plain
                type="danger"
                size="small"
                @click="delexam(scope.row.exam_id)"
                :class="!scope.row.hasResult ? 'button2' : 'button1'"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          v-model:current-page="saosuo02.pageNum"
          v-model:page-size="saosuo02.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="saosuo02.total"
          @size-change="handleSizeChange02"
          @current-change="handleCurrentChange02"
          style="margin-top: 20px; justify-content: center"
        />
      </el-tab-pane>
    </el-tabs>
    <!-- 创建试卷对话框 -->
    <el-dialog title="创建考试" v-model="createDialogVisible" width="30%">
      <el-form
        :model="choti"
        :rules="rules"
        ref="examForm"
        label-width="80px"
        class="custom-form"
      >
        <el-form-item label="试卷编号" prop="name" v-if="choti.exam_id">
          <el-input v-model="choti.exam_id" disabled />
        </el-form-item>
        <!-- 试卷名称输入框 -->
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="choti.name" disabled />
        </el-form-item>
        <el-form-item label="考试名称" prop="exam_name">
          <el-input v-model="choti.exam_name" placeholder="考试名称" />
        </el-form-item>
        <!-- 考试时间选择器 -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            type="datetime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="HH:mm:ss"
            v-model="choti.startTime"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            type="datetime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            date-format="YYYY/MM/DD ddd"
            time-format="HH:mm:ss"
            v-model="choti.endTime"
          />
        </el-form-item>
        <!-- 试卷类型下拉框 -->
        <el-form-item label="试卷类型" prop="leibie">
          <el-select-v2
            v-model="choti.leibie"
            disabled
            :options="initials"
            placeholder="试卷类型"
            clearable
          />
        </el-form-item>
        <!-- 考试班级选择器 -->
        <el-form-item label="考试班级" prop="leibie2">
          <el-select-v2
            multiple
            hide-required-asterisk
            v-model="choti.leibie2"
            :options="banlie"
            placeholder="选择班级"
            clearable
          />
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <!-- 取消按钮 -->
          <el-button @click="quxiaoExam">取 消</el-button>
          <!-- 确定按钮 -->
          <el-button type="primary" @click="createExam">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { findClassroomByClassId } from "@/api/kaoshi/index";
//路由
import router from "@/router";
import { ref, onMounted } from "vue";
import { ElMessage, ElForm } from "element-plus";
import {
  findExamInfo,
  findclass,
  addExamInfo,
  deleteExamInfo,
  banjiget,
} from "@/api/kaoshi/kaoguan.js";
import dayjs from "dayjs";

import { useUserInfoStore } from "@/store/user.js";
const userInfoStore = useUserInfoStore();

const activeName = ref("first");

const tableData02 = ref([]);

//查询专业课程
import { direction } from "@/api/common/work/courseManager.js";

// 搜索条件对象
// console.log(userInfoStore.userInfo);
const saosuo = ref({
  xianguan: "",
  leibie: userInfoStore.userInfo.majorId,
  pageNum: 1,
  pageSize: 10, 
  total: 0,
});

const saosuo02 = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  classId: 0,
  leibie: userInfoStore.userInfo.majorId,
});

// 班级列表
const banlie = ref([]);

// 表格数据
const tableData = ref([]);

// 创建试卷对话框显示状态
const createDialogVisible = ref(false);

// 创建试卷表单数据对象
const choti = ref({
  name: "",
  startTime: "",
  endTime: "",
  leibie: "",
  paper_id: "",
  leibie2: [],
  exam_name: "",
  exam_id: "",
  pageNum: 1,
  pageSize: 10,
  total: 0,
  classId: 0,
});

const setexamRoom02 = async () => {
console.log(saosuo02.value);
    let data = await findClassroomByClassId(saosuo02.value);
    if (data && data.data && data.data.list) {
      tableData02.value = data.data.list;
      saosuo02.value.total = data.data.total;
    }
};
//考试分页
const handleSizeChange02 = (val: number) => {
  saosuo02.value.pageSize = val; // 更新 pageSize
  setexamRoom02(); // 重新获取考试数据
};

const handleCurrentChange02 = (val: number) => {
  saosuo02.value.pageNum = val; // 更新 pageNum
  setexamRoom02(); // 重新获取考试数据
};
// 删除考试信息操作
const delexam = async (ss) => {
  try {
    await deleteExamInfo(ss); // 假设这是你的删除 API 方法
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    // 重新获取考试数据
    setexamRoom02();
  } catch (error) {
    console.error("Error deleting exam info:", error);
    ElMessage({
      message: "删除失败",
      type: "error",
    });
  }
};

// 格式化创建时间
const formattedCreateTime = (createTime) => {
  return dayjs(createTime).format("YYYY-MM-DD HH:mm:ss");
};

const formattedCreateTime2 = (createTime) => {
  return dayjs(createTime).format("YYYY-MM-DD HH:mm:ss");
};

// 表单校验规则
const rules = ref({
  name: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
  timejilu: [{ required: true, message: "请选择考试时间", trigger: "change" }],
  leibie2: [{ required: true, message: "请选择考试班级", trigger: "change" }],
});

// 获取表单实例
const examForm = ref<InstanceType<typeof ElForm>>();

// 组件挂载时执行的初始化操作
onMounted(() => {
  directionss(); // 获取试卷类型
  banleibie(); // 获取班级列表
  setshuju1(); // 获取试卷数据
  setexamRoom02();
});
// 获取试卷数据
const setshuju1 = async () => {
  try {
    let data = await findExamInfo(saosuo.value);
    // console.log("findExamInfo response:", data); // 添加日志输出
    tableData.value = data.data.list;
    saosuo.value.total = data.data.total;
  } catch (error) {
    ElMessage({
      message: "获取考试信息失败",
      type: "error",
    });
  }
};

// 获取班级列表
const banleibie = async () => {
  try {
    let res = await banjiget(userInfoStore.userInfo.userId);
    // console.log(res.data);
    if (res.data) {
      banlie.value.push(
        ...res.data.map((item) => ({
          value: item.classId,
          label: item.className,
        }))
      );
    } else {
      console.error("res.data is null or undefined");
    }
  } catch (error) {
    console.error("Error fetching direction:", error);
  }
};

// 编辑试卷操作
const handleEdit = (index, row) => {
  router.push({
    path: "/testpaper",
    query: { eid: row.examination_id },
  });
};

// 预览试卷操作
const handleLook = (index, row) => {
  router.push({
    path: "/testpaper",
  });
};

// 创建试卷操作
const handlePreview = (index, row) => {
  choti.value.name = row.examination_name;
  createDialogVisible.value = true;
  choti.value.paper_id = row.examination_id;
  choti.value.leibie = row.direction_id;
};
// 修改考场信息
const bianji = (index, row) => {
  // 显示编辑对话框
  createDialogVisible.value = true;

  // // 将行数据赋值给 choti 对象
  choti.value.name = row.examination_name;
  choti.value.paper_id = row.examination_id;
  choti.value.leibie = row.direction_id;
  choti.value.leibie2 = row.sys_class_id
    ? row.sys_class_id.split(",").map(Number)
    : []; // 将字符串转换为数组
  choti.value.startTime = dayjs(row.start_time).format("YYYY-MM-DD HH:mm:ss");
  choti.value.endTime = dayjs(row.end_time).format("YYYY-MM-DD HH:mm:ss");
  choti.value.exam_name = row.exam_name;
  choti.value.exam_id = row.exam_id;
};
// 创建考场确认操作
const createExam = async () => {
  examForm.value?.validate(async (valid) => {
    if (valid) {
      let xx = {
        paperId: choti.value.paper_id,
        startTime: choti.value.startTime,
        endTime: choti.value.endTime,
        sysClassId: String(choti.value.leibie2),
        examName: choti.value.exam_name,
        examId: choti.value.exam_id,
      };
      let data = await addExamInfo(xx);
      console.log(activeName.value);
      if (choti.value.exam_id != null && choti.value.exam_id != undefined) {
        if (activeName.value == "first") {
          if (data.data === true) {
            ElMessage({
              message: "创建成功",
              type: "success",
            });
          } else {
            ElMessage({
              message: "创建失败",
              type: "error",
            });
          }
        }

        if (activeName.value == "second") {
          if (data.data === true) {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
          } else {
            ElMessage({
              message: "编辑失败",
              type: "error",
            });
          }
        }
      }
      choti.value = {
        name: "",
        startTime: "",
        endTime: "",
        leibie: "",
        paper_id: "",
        leibie2: [],
        exam_name: "",
        exam_id: "",
        pageNum: 1,
        pageSize: 10,
        total: 0,
        classId: 0,
      };
      createDialogVisible.value = false;
    } else {
      ElMessage({
        showClose: true,
        message: "请按照规则输入",
        type: "error",
      });
    }
  });
};

//取消创建考场操作
const quxiaoExam = () => {
  choti.value = {
    name: "",
    startTime: "",
    endTime: "",
    leibie: "",
    paper_id: "",
    leibie2: [],
    exam_name: "",
    exam_id: "",
    pageNum: 1,
    pageSize: 10,
    total: 0,
    classId: 0,
  };
  createDialogVisible.value = false;
};

// 搜索操作
const performSearch = () => {
  console.log(saosuo.value)
  setshuju1();
};

// 分页大小改变时的操作
const handleSizeChange = (val: number) => {
  saosuo.value.pageSize = val; // 更新 pageSize
  setshuju1(); // 重新获取试卷数据
};

// 当前页码改变时的操作
const handleCurrentChange = (val: number) => {
  saosuo.value.pageNum = val; // 更新 pageNum
  setshuju1(); // 重新获取试卷数据
};

// 试卷类型选项
const initials = ref([]);

// 获取试卷类型
const directionss = async () => {
  try {
    let res = await direction();
    if (res.data) {
      initials.value = res.data.map((item) => ({
        value: item.directionId,
        label: item.directionName,
      }));
    }
  } catch (error) {
    console.error("Error fetching direction:", error);
  }
};
</script>

<style lang="scss" scoped>
.biaoge {
  padding: 16px;
}

.head {
  display: inline-block;
  width: 100%;
  height: 50px;
  line-height: 50px;
  background-color: #f5f5f5;
  border-radius: 5px;
  color: #333;
  font-size: 20px;
  margin-bottom: 16px;
  padding-left: 16px;
  font-weight: 600;
}

.demo-form-inline {
  width: 500px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  gap: 20px;

  .el-input,
  .el-form-item {
    width: 300px;
    margin-right: 0px;
  }
  .el-button {
    margin-top: 10px;
  }
}

.el-select-v2,
.el-select {
  input {
    height: 36px;
    line-height: 36px;
    padding: 0 15px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  }

  &:focus-within {
    input {
      border-color: #409eff;
    }
  }
}
.button1 {
  //隐藏样式
  visibility: hidden;
}
</style> 